/**
 *
 */
package com.xbang.core.utils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * @author dev.zhang
 * @author Downpour
 * @author Carl
 */
public abstract class FreeMarkerUtils {

	private static final Log logger = LogFactory.getLog(FreeMarkerUtils.class);

	/**
	 * 
	 * @param root
	 * @param filePath
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String processTemplateFile(Map root, String filePath) {

		StringWriter sw = new StringWriter();

		String result = "";

		Configuration cfg = new Configuration();
		cfg.setEncoding(Locale.CHINA, "UTF-8");

		try {
			cfg.setDirectoryForTemplateLoading(new ClassPathResource("template").getFile());
		} catch (IOException e) {
			logger.error(e.getMessage());

			throw new RuntimeException("FreeMarker template directory error");
		}

		try {

			Template ftl = cfg.getTemplate(filePath, Locale.CHINA, "UTF-8");

			try {
				ftl.process(root, sw);
				result = sw.toString();
			} catch (TemplateException e) {
				logger.error("tempalte exception:" + e.getMessage());
				throw new RuntimeException("FreeMarker template process failed" + e.getMessage());
			}

		} catch (IOException e) {

			logger.error(e.getMessage());
			throw new RuntimeException("FreeMarker template file parse error");

		} finally {

			try {
				sw.close();
			} catch (IOException e) {
				logger.error(e.getMessage());
			}
		}

		return result;
	}

}
